package cn.xie.blog.serverutil.util;

import cn.xie.blog.serverutil.constant.common.EncryptConstant;
import lombok.experimental.UtilityClass;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

import static cn.xie.blog.serverutil.constant.common.EncryptConstant.ITERATION_COUNT;
import static cn.xie.blog.serverutil.constant.common.EncryptConstant.KEY_LENGTH;

/**
 * @author: xiaoxie
 * create: 2025-04-22 18:32
 * @BelongsProject: blog-parent
 * @BelongsPackage: cn.xie.blog.serverutil.util
 * description: 密码加密工具类
 */
@UtilityClass
public  class EncryptUtils {

    // 生成盐值
    public static String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[EncryptConstant.SALT_LENGTH];
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    // 加密密码
    public static String encryptPassword(String password, String salt)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), Base64.getDecoder().decode(salt),
                ITERATION_COUNT, KEY_LENGTH);
        byte[] hash = factory.generateSecret(spec).getEncoded();
        return Base64.getEncoder().encodeToString(hash);
    }

    // 验证密码
    public static boolean verifyPassword(String password, String salt, String encryptedPassword)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        String encryptedPasswordToVerify = encryptPassword(password, salt);
        return encryptedPassword.equals(encryptedPasswordToVerify);
    }

}
